/*
 * File Name：CameraActivity.java
 * Copyright：Copyright 2008-2013 CiWong.Inc. All Rights Reserved.
 * Description： CameraActivity.java
 * Modify By：RES-KUNZHU
 * Modify Date：2013-5-16
 * Modify Type：Add
 */
package com.ciwong.mobilelib.ui;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.ImageUtils;
import com.ciwong.mobilelib.R;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.BaseSystem;
import com.ciwong.mobilelib.utils.BaseSystem.CallBack;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.widget.CWCamera;
import com.ciwong.mobilelib.widget.ToucheFocusCameraPreview;

/**
 * 照相机
 * 
 * @author RES-KUNZHU
 * @version ciwong v.1.0 2013-5-16
 * @since ciwong v.1.0
 */
public class CameraActivity extends BaseActivity implements OnClickListener
{
    /**
     * 拍一拍
     */
    public static final int JUMP_TYPE_PAIYIPAI = 1;

    /**
     * 跳转过来的类型
     */
    private int jumpType = -1;

    /**
     * 相片保存路径 标示
     */
    public static final String PAHT_FLAG_PATH = "PAHT_FLAG_PATH";

    /**
     * 50
     */
    public static final int WIDTH_FIFITY = 50;

    private final int mImgCode = 0;

    private final int mFlashLightAuto = 1;

    private final int mFlahLightOpen = 2;

    private final int mFlashLightClose = 3;

    /**
     * 打开资源库
     */
    private ImageView mIvSource;

    /**
     * 拍照
     */
    private ImageView mIvTakePhoto;

    /**
     * 预览
     */
    private ToucheFocusCameraPreview mCameraPreview;

    private Button mCameraCancel;

    private TextView flashlight, flashlightTyp1, flashlightTyp2, cameraTitle;

    private View mFlashlightContainer;

    private ImageView mSelectCamera;

    private Animation mLeftEnter, mLeftExit;

    /**
     * 相机
     */
    private CWCamera mCamera;

    @Override
    protected void preCreate()
    {

    }

    @Override
    public int setView()
    {
        return R.layout.camera;
    }

    @Override
    public void findViews()
    {
        mCamera = CWCamera.instance();
        mIvSource = (ImageView) findViewById(R.id.camera_source);
        mIvTakePhoto = (ImageView) findViewById(R.id.camera_take_photo);
        mCameraPreview = (ToucheFocusCameraPreview) findViewById(R.id.camera_camera);
        mCameraCancel = (Button) findViewById(R.id.camera_cancel);
        flashlight = (TextView) findViewById(R.id.flashlight);
        mFlashlightContainer = findViewById(R.id.flashlightContainer);
        flashlightTyp1 = (TextView) findViewById(R.id.flashlightTyp1);
        flashlightTyp2 = (TextView) findViewById(R.id.flashlightTyp2);
        cameraTitle = (TextView) findViewById(R.id.cameraTitle);
        mSelectCamera = (ImageView) findViewById(R.id.selectCamera);
    }

    @Override
    public void initEvent()
    {
        mIvSource.setOnClickListener(this);
        mIvTakePhoto.setOnClickListener(this);
        mCameraCancel.setOnClickListener(this);
        flashlight.setOnClickListener(this);
        flashlightTyp1.setOnClickListener(this);
        flashlightTyp2.setOnClickListener(this);
        mSelectCamera.setOnClickListener(this);
        mCamera.setTakePicCallback(new CWCamera.TakePic()
        {
            @Override
            public void takePic(Bitmap mBitmap)
            {
                final int degrees = -90;
                final int defaultValues = 90;
                super.takePic(mBitmap);
                if (mBitmap != null)
                {
                    Matrix m = new Matrix();
                    m.setRotate(isFront() ? degrees : defaultValues);
                    Bitmap finalBit = Bitmap.createBitmap(mBitmap, 0, 0,
                            mBitmap.getWidth(), mBitmap.getHeight(), m, true);
                    mBitmap.recycle();
                    mBitmap = null;
                    String sendPhotoPath = ImageUtils.saveBitmapCamera(
                            finalBit, BaseSystem.getImagePath(CameraActivity.this));

                    finalBit.recycle();
                    finalBit = null;
                    getPicSuccess(sendPhotoPath);
                }
                else
                {
                    CWLog.e("camera", "takepicture failed");
                    getPicSuccess(null);
                    BaseSystem.alertDialog(CameraActivity.this, R.string.tips,
                            R.string.no_camera_permission,
                            R.string.confirm_finish, new BaseSystem.CallBack()
                            {
                                @Override
                                public void callback()
                                {
                                    CameraActivity.this.finish();
                                }
                            });
                }
                mIvTakePhoto.setEnabled(true);
            }

            // @Override
            // public void takePic(byte[] picBytes)
            // {
            // String sendPhotoPath = CWSystem.getImagePath() + "/"
            // + System.currentTimeMillis();
            // FileUtils.save(new File(sendPhotoPath), picBytes);
            //
            // getPicSuccess(sendPhotoPath);
            // mIvTakePhoto.setEnabled(true);
            // }

            @Override
            public void failed()
            {

                if (!isFinishing())
                {
                    BaseSystem.alertDialog(CameraActivity.this, R.string.tips,
                            R.string.no_camera_permission,
                            R.string.confirm_finish, new BaseSystem.CallBack()
                            {

                                @Override
                                public void callback()
                                {
                                    CameraActivity.this.finish();
                                }
                            });
                    mIvTakePhoto.setEnabled(true);
                }
            }
        });

    }

    @Override
    public void init()
    {
        // setFlingFinish(false);
        hideTitleBar();
        getLatestPhoto();
        int tag = CWSys.getSharedInt("FLASHLIGHT_MODE", mFlashLightAuto);
        changeFLashlight(tag, false);
        if (!CWCamera.instance().canOpenFacing())
        {
            mSelectCamera.setVisibility(View.GONE);
        }

    }

    @Override
    public void loadData()
    {

    }

    private void leftEnter()
    {
        if (mLeftEnter == null)
        {
            mLeftEnter = AnimationUtils
                    .loadAnimation(this, R.anim.bottom_enter);
        }
        mFlashlightContainer.clearAnimation();
        mFlashlightContainer.setVisibility(View.VISIBLE);
        mFlashlightContainer.startAnimation(mLeftEnter);
    }

    private void leftExit()
    {
        if (mLeftExit == null)
        {
            mLeftExit = AnimationUtils.loadAnimation(this, R.anim.bottom_exit);
            mLeftExit.setAnimationListener(new AnimationListener()
            {

                @Override
                public void onAnimationStart(Animation animation)
                {

                }

                @Override
                public void onAnimationRepeat(Animation animation)
                {

                }

                @Override
                public void onAnimationEnd(Animation animation)
                {
                    mFlashlightContainer.clearAnimation();
                    mFlashlightContainer.setVisibility(View.GONE);
                }
            });
        }
        mFlashlightContainer.clearAnimation();
        mFlashlightContainer.setVisibility(View.VISIBLE);
        mFlashlightContainer.startAnimation(mLeftExit);
    }

    private void pause()
    {
        mCameraPreview.getCameraPreview().enablePreview(false);
        mCamera.stopPreview();
        mCameraPreview.unRegisterListener();
    }

    private void resume()
    {
        mCameraPreview.getCameraPreview().enablePreview(true);
        mCamera.startPreview(this);
        mCameraPreview.registerListener();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        pause();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        resume();
    }

    private int getFlashlightTag(View view)
    {
        int flashlightTag = mFlashLightAuto;
        try
        {
            flashlightTag = Integer.parseInt(view.getTag().toString());
        }
        catch (Exception e)
        {
            flashlightTag = mFlashLightAuto;
        }
        return flashlightTag;
    }

    /**
     * 
     * 闪光灯
     * 
     * @param tag
     * @param anim
     */
    private void changeFLashlight(int tag, boolean anim)
    {
        switch (tag)
        {
            case mFlashLightAuto:
                flashlight.setText(R.string.flashlight_auto);
                CWCamera.instance().setFlashMode(
                        Camera.Parameters.FLASH_MODE_AUTO);
                break;
            case mFlashLightClose:
                flashlight.setText(R.string.flashlight_close);
                CWCamera.instance().setFlashMode(
                        Camera.Parameters.FLASH_MODE_OFF);
                break;
            case mFlahLightOpen:
                flashlight.setText(R.string.flashlight_open);
                CWCamera.instance().setFlashMode(
                        Camera.Parameters.FLASH_MODE_ON);
                break;
        }
        flashlight.setTag(tag);
        CWSys.setSharedInt("FLASHLIGHT_MODE", tag);
        if (anim)
        {
            leftExit();
        }
        cameraTitle.setVisibility(View.VISIBLE);
    }

    private boolean isFront()
    {
        boolean isFront = false;
        if (mSelectCamera.getTag() != null)
        {
            isFront = Boolean.parseBoolean(mSelectCamera.getTag().toString());
        }
        return isFront;
    }

    @Override
    public void onClick(View v)
    {
        int vId = v.getId();
        if (vId == R.id.camera_source)
        {
//            ActivityJumpManager.jumpToSysAlbum(CameraActivity.this, mImgCode);
        }
        else if (vId == R.id.camera_take_photo)
        {
            mIvTakePhoto.setEnabled(false);
            mCamera.takePicture();
        }
        else if (vId == R.id.camera_cancel)
        {
            finish();
        }
        else if (vId == R.id.selectCamera)
        {
            boolean isFront = isFront();
            CWCamera.instance().release();
            if (!isFront)
            {
                try
                {
                    if (CWCamera.instance().openFacing())
                    {
                        CWCamera.instance().startPreview(this);
                        mSelectCamera.setTag(true);
                    }
                }
                catch (Exception e)
                {
                    BaseSystem.alertDialog(CameraActivity.this, R.string.tips,
                            R.string.no_camera_permission,
                            R.string.confirm_finish, new BaseSystem.CallBack()
                            {

                                @Override
                                public void callback()
                                {
                                    CameraActivity.this.finish();
                                }
                            });
                }

            }
            else
            {
                try
                {
                    if (CWCamera.instance().open())
                    {
                        CWCamera.instance().startPreview(this);
                        mSelectCamera.setTag(false);
                    }
                }
                catch (Exception e)
                {
                    BaseSystem.alertDialog(CameraActivity.this, R.string.tips,
                            R.string.no_camera_permission,
                            R.string.confirm_finish, new CallBack()
                            {

                                @Override
                                public void callback()
                                {
                                    CameraActivity.this.finish();
                                }
                            });
                }

            }
        }
        else if (vId == R.id.flashlight)
        {
            if (mFlashlightContainer.getVisibility() == View.VISIBLE)
            {
                leftExit();
                cameraTitle.setVisibility(View.VISIBLE);
            }
            else
            {
                cameraTitle.setVisibility(View.GONE);
                int tag = getFlashlightTag(flashlight);
                if (tag == mFlashLightAuto)
                {
                    flashlightTyp1.setText(R.string.flashlight_open);
                    flashlightTyp1.setTag(mFlahLightOpen);
                    flashlightTyp2.setText(R.string.flashlight_close);
                    flashlightTyp2.setTag(mFlashLightClose);
                }
                else if (tag == mFlashLightClose)
                {
                    flashlightTyp1.setText(R.string.flashlight_auto);
                    flashlightTyp1.setTag(mFlashLightAuto);
                    flashlightTyp2.setText(R.string.flashlight_open);
                    flashlightTyp2.setTag(mFlahLightOpen);
                }
                else
                {
                    flashlightTyp1.setText(R.string.flashlight_auto);
                    flashlightTyp1.setTag(mFlashLightAuto);
                    flashlightTyp2.setText(R.string.flashlight_close);
                    flashlightTyp2.setTag(mFlashLightClose);
                }
                leftEnter();
            }
        }
        else if (vId == R.id.flashlightTyp1)
        {
            int tag = getFlashlightTag(flashlightTyp1);
            changeFLashlight(tag, true);
        }
        else if (vId == R.id.flashlightTyp2)
        {
            int tag = getFlashlightTag(flashlightTyp2);
            changeFLashlight(tag, true);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mImgCode && resultCode == Activity.RESULT_OK)
        {
            try
            {
                Uri uri = data.getData();
                String path = null;
                Cursor c = getContentResolver().query(uri,
                        new String[]{MediaStore.Images.Media.DATA}, null, null,
                        null);

                if (c != null && c.moveToNext())
                {
                    path = c.getString(0);
                    c.close();
                }
                else
                {
                    path = uri.getPath();
                }
                getPicSuccess(path);

            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * 
     * 获取图片成功后，跳转
     * 
     * @param path
     */
    private void getPicSuccess(String path)
    {
        Intent intentSend = new Intent();
        intentSend.putExtra(PAHT_FLAG_PATH, path);
        setResult(RESULT_OK, intentSend);
        finish();
    }

    /**
     * 获取最近拍摄的照片，显示出来
     * 
     */
    private void getLatestPhoto()
    {
        if (mIvSource.getDrawable() != null)
        {
            return;
        }
        executeDBThread(new Runnable()
        {
            public void run()
            {
                Cursor cursor = getContentResolver().query(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
                        null, null,
                        MediaStore.Images.Media.DATE_TAKEN + " desc");
                if (cursor != null)
                {
                    cursor.moveToFirst();
                    if (cursor.getCount() > 0)
                    {
                        final String path = cursor.getString(cursor
                                .getColumnIndex(MediaStore.Images.Media.DATA));
                        cursor.close();
                        final Bitmap bitmap = ImageUtils.getImage(path,
                                mIvSource.getWidth() == 0 ? WIDTH_FIFITY
                                        : mIvSource.getWidth());
                        runOnUiThread(new Runnable()
                        {
                            public void run()
                            {
                                mIvSource.setImageBitmap(bitmap);
                            }
                        });
                    }
                }
                else
                {
                    runOnUiThread(new Runnable()
                    {
                        public void run()
                        {
                            // mIvSource.setImageResource(R.drawable.cw_icon);
                        }
                    });
                }
            }
        }, ThreadTask.ThreadPeriod.PERIOD_MIDDLE);
    }

}
